package com.glfx;

import com.glfx.utils.FileUtils;
import nl.siegmann.epublib.domain.Book;
import nl.siegmann.epublib.domain.Resource;
import nl.siegmann.epublib.domain.SpineReference;
import nl.siegmann.epublib.epub.EpubReader;
import org.jsoup.Jsoup;
import org.jsoup.internal.StringUtil;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.junit.Test;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 柧麟浮休
 * @date 2022/7/7
 */
public class NovelCreateContentsXml {

    @Test
    public void createXml() throws Exception {
        File novelFile = new File("F:\\lightNovel\\在异世界迷宫开后宫.epub");
        EpubReader reader = new EpubReader();
        Book book = reader.readEpub(new FileInputStream(novelFile));
        List<SpineReference> spineReferences = book.getSpine().getSpineReferences();
        List<String> names = new ArrayList<>();
        for (SpineReference spineReference : spineReferences) {
            Resource resource = spineReference.getResource();
            String href = resource.getHref();
            byte[] data = resource.getData();
            Document parse = Jsoup.parse(new String(data));
            Elements h1 = parse.getElementsByTag("h1");
            String text = h1.text();
            if (!StringUtil.isBlank(href) && !StringUtil.isBlank(text)) {
                names.add(href + "," + text);
            }
        }
        createContentsXml(names);
    }

    private void createContentsXml(List<String> names) {
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i <= names.size() - 1; i++) {
            String[] split = names.get(i).split(",");
            String href = split[0];
            String text = split[1];
            sb.append("    ").append("<navPoint id=\"navPoint-").append(i).append("\" playOrder=\"").append(i).append("\">").append("\n")
                    .append("    ").append("  ").append("<navLabel>").append("\n")
                    .append("    ").append("  ").append("  ").append("<text>").append(text).append("</text>").append("\n")
                    .append("    ").append("  ").append("</navLabel>").append("\n")
                    .append("    ").append("  ").append("<content src=\"").append(href).append("\"/>").append("\n")
                    .append("    ").append("</navPoint>").append("\n");
        }
        FileUtils.writeFileFromStr(sb.toString(), "C:\\Users\\Administrator\\Desktop\\test\\test.txt");
    }

}
